const { app, BrowserWindow, Menu, dialog } = require('electron');
const path = require('path');
const fs = require('fs');

function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true
        }
    });

    mainWindow.loadFile('index.html');
    mainWindow.webContents.openDevTools();

    // 创建菜单栏
    const template = [
        {
            label: '文件',
            submenu: [
                {
                    label: '打开',
                    click: async () => {
                        const { canceled, filePaths } = await dialog.showOpenDialog(mainWindow, {
                            filters: [
                                { name: '文本文件', extensions: ['txt'] }
                            ]
                        });
                        if (!canceled) {
                            const filePath = filePaths[0];
                            const text = fs.readFileSync(filePath, 'utf8');
                            mainWindow.webContents.send('open-file', text);
                        }
                    }
                },
                {
                    label: '保存',
                    click: () => {
                        mainWindow.webContents.send('save-file');
                    }
                },
                {
                    label: '退出',
                    click: () => {
                        app.quit();
                    }
                }
            ]
        }
    ];

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
}

app.whenReady().then(() => {
    createWindow();

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit();
});